//
//  FindQuoteVC.m
//  zhiche--delivery
//
//  Created by 王亚陆 on 16/5/28.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "FindQuoteVC.h"
#import "QuoteCell.h"
#import "NewBtn.h"
#import "Common.h"
#import "QuoteListVC.h"
#import <MJRefresh.h>
#import "RootViewController.h"
#import "CancelViewController.h"
#import "WKProgressHUD.h"
#import "RLNetworkHelper.h"
#import "NullView.h"
#import "QuoteDetailVC.h"
#import "NewQuoteDetailVC.h"

@interface FindQuoteVC ()
{
    Common *Com;
    UIView * nav;
    UITableView * table;
    NSMutableArray * dataSouceArr;
    NSMutableDictionary * dataSouceDic;
    int page ;
    int totalPage;
    RootViewController * TabBar;
    UIView * NoNetWorkView;
    WKProgressHUD *hud;
    NullView * nullView;
}


@end

@implementation FindQuoteVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = GrayColor;
    nav = [self createNav:@"查看发单"];
    Com = [[Common alloc]init];
    page = 1;
    totalPage = 1;
    [self.view addSubview:nav];
    TabBar = [RootViewController defaultsTabBar];

    dataSouceArr = [[NSMutableArray alloc]init];
    dataSouceDic = [[NSMutableDictionary alloc]init];

    nullView = [[NullView  alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight - 64 ) andTitle:@"暂无订单"];
    nullView.backgroundColor = GrayColor;
    nullView.label.text = @"暂无订单";
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, Main_Width,Main_height-64) style:UITableViewStylePlain];
    [table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    table.backgroundColor = GrayColor;
    table.delegate = self;
    table.dataSource = self;
    [table.mj_header beginRefreshing];
    table.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    table.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
    [self.view addSubview:table];
    //无网路状态和加载状态
    [self createNetWorkAndStatue];

}



-(void)createNetWorkAndStatue{
    //创建无网络状态view

    NoNetWorkView = [Com noInternet:@"网络异常" and:self action:@selector(NoNetPressBtn) andCGreck:CGRectMake(0, 0, Main_Width, Main_height-64)];
    [table addSubview:NoNetWorkView];
    //判断是否有网
    [self judgeNetWork];
}

//判断是否有网
-(void)judgeNetWork{
    if (![RLNetworkHelper isConnectedToNetwork]) {
        NoNetWorkView.hidden = NO;
    }
    else{
        NoNetWorkView.hidden = YES;
        [self loadData];
    }
}

//无网络状态
-(void)NoNetPressBtn{
    if ([RLNetworkHelper isConnectedToNetwork]) {
        NoNetWorkView.hidden = YES;
        [self loadData];
    }
}

-(void)downRefresh{
    
    [table.mj_header endRefreshing];
    [table.mj_footer endRefreshing];
    page = 1;
    
    [self judgeNetWork];
    NSLog(@"刷新");
}
-(void)upRefresh{
    
    if (page!=totalPage) {
        page ++;
        [self judgeNetWork];
        [table.mj_footer endRefreshing];
    }else{
        table.mj_footer.state = MJRefreshStateNoMoreData;
    }
    [table.mj_header endRefreshing];
    NSLog(@"加载%d%d",page,totalPage);
}

-(void)loadData{
    
    int pageSize = 10;
    hud = [WKProgressHUD showInView:self.view withText:@"加载中" animated:YES];
    BOOL isNet = YES;
    NSString * string = [NSString stringWithFormat:@"%@?pageNo=%d&pageSize=%d",Order_Published_Url,page,pageSize];
    if (isNet) {
        [Common requestWithUrlString:string contentType:@"application/json" finished:^(id responseObj){
            
            dataSouceDic = responseObj[@"data"];
            NSMutableArray * arr = [NSMutableArray arrayWithArray:dataSouceDic[@"orders"]];
            if ([arr count]>0) {
                if (page == 1) {
                    [dataSouceArr removeAllObjects];
                    dataSouceArr = arr;
                }else{
                    for (int i=0; i<[arr count]; i++) {
                        
                        [dataSouceArr addObject:arr[i]];
                    }
                }
                
                [nullView removeFromSuperview];
                
            }else{
                [dataSouceArr removeAllObjects];
//                [table addSubview:nullView];
            }
            
            //        dataSouceArr = dataSouceDic[@"orders"];
            totalPage = [dataSouceDic[@"page"][@"totalPage"] intValue];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [hud dismiss:YES];
                [table reloadData];
            });
            
        } failed:^(NSString *errorMsg) {
            NSLog(@"%@",errorMsg);
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [hud dismiss:YES];
            });

        }];
    }
    
}


-(void)viewWillAppear:(BOOL)animated{
    [TabBar setTabBarHidden:YES];
    
    self.isTwo = YES;

    
    
}

-(void)viewDidDisappear:(BOOL)animated{
    
//    self.isTwo = NO;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    static NSString *str=@"str";
    
    QuoteCell * cell =  [tableView dequeueReusableCellWithIdentifier:str];
    if (cell ==nil) {
        cell = [[QuoteCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

//    NSLog(@"%ld",(long)indexPath.row);
    [cell showInfo:dataSouceArr[indexPath.row]];
    
    cell.Btn2.indexpath = indexPath;
//    cell.Btn3.indexpath = indexPath;
    [cell.Btn2 addTarget:self action:@selector(pressBtn2:) forControlEvents:UIControlEventTouchUpInside];
//    [cell.Btn3 addTarget:self action:@selector(pressBtn3:) forControlEvents:UIControlEventTouchUpInside];

    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NewQuoteDetailVC * detailVC = [[NewQuoteDetailVC alloc]init];
    detailVC.orderId = dataSouceArr[indexPath.row][@"id"];
    detailVC.orderTitleString = @"订单详情";

    [self.navigationController pushViewController:detailVC animated:YES];
    

    
}

-(void)pressBtn2:(NewBtn*)sender{
    
//    int status = [dataSouceArr[sender.indexpath.row][@"status"]intValue];
//    if (status == 20) {
//        
//    CancelViewController * cancel = [[CancelViewController alloc]init];
//    cancel.integer = [dataSouceArr[sender.indexpath.row][@"id"] integerValue];
//    [self.navigationController pushViewController:cancel animated:YES];
//    }else{
//        
        UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:@"确定是否取消订单" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * action =[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            
        NSLog(@"点击的确定按钮");
            
        NSMutableDictionary * dicUrl = [[NSMutableDictionary alloc]init];
        [dicUrl setObject:dataSouceArr[sender.indexpath.row][@"id"] forKey:@"orderid"];
        [dicUrl setObject:@"" forKey:@"reason"];
            
            dispatch_async(dispatch_get_main_queue(), ^{

                NSLog(@"%@",Mine_Order_Cancel);
                
                [Common afPostRequestWithUrlString:Mine_Order_Cancel parms:dicUrl finishedBlock:^(id responseObj) {
                    
                    NSMutableDictionary * dicObj =[NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableContainers error:nil];
                    NSLog(@"取消订单%@",dicObj);
                    NSString * string = [NSString stringWithFormat:@"%@",dicObj[@"success"]];
                    if ([string isEqualToString:@"1"]) {
                        page = 1;
                        [self loadData];
                    }
                    
                } failedBlock:^(NSString *errorMsg) {
                }];

            });
        }];
        UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

        }];
        [alert addAction:action1];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
//    }

    NSLog(@"Btn2:%ld",(long)sender.indexpath.row);
}
-(void)pressBtn3:(NewBtn*)sender{
   
//    QuoteListVC * listVC= [[QuoteListVC alloc]init];
//    
//    listVC.orderID = dataSouceArr[sender.indexpath.row][@"id"];
//    [self.navigationController pushViewController:listVC animated:YES];

    
    QuoteDetailVC * detailVC = [[QuoteDetailVC alloc]init];
    detailVC.orderId = dataSouceArr[sender.indexpath.row][@"id"];
    detailVC.orderTitleString = @"订单详情";
    [self.navigationController pushViewController:detailVC animated:YES];
    
    NSLog(@"Btn3:%ld",(long)sender.indexpath.row);
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    225
//    return    (indexPath.row == dataSouceArr.count-1)?225*kHeight:235*kHeight;
    return    (indexPath.row == dataSouceArr.count-1)?190*kHeight:200*kHeight;

}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return dataSouceArr.count;
//    return 2;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)createUIAlertController:(NSString*)title
{
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:action1];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

@end
